<script setup>
import {
  TreeListAPI,
  moldDdlAPI,
  AddCategoryAPI,
  DelCategoryAPI,
  AddDataAPI,
  GetListAPI,
  EditDataAPI,
  GetViewAPI,
  DelDataAPI,
  GetCategoryViewAPI,
  EditCategoryDataAPI,
} from "@/api/mold/edger";
import SubmitForm from "./submitForm.vue";
const { proxy } = getCurrentInstance();

/**
 * 字典查询
 */
const { sys_tool_staus } = proxy.useDict("sys_tool_staus");

/**
 * 模糊查询枚举
 */
const selectList = ref([
  { type: "日期范围" },
  { label: "模具名称", model: "mouldName", type: "输入框" },
  {
    label: "模具类型",
    model: "mouldType",
    type: "模具类型",
  },
  {
    label: "状态",
    model: "status",
    type: "下拉单选",
    opt: sys_tool_staus,
  },
  { label: "制造厂商", model: "factoryName", type: "输入框" },
]);
/**
 * 表单实例
 */
const ruleFormRef = ref(null);
/**
 * 表单
 */
const ruleForm = ref({});
/**
 * 表格枚举
 */
const columns = ref([
  { label: "模具名称", prop: "mouldName", width: "120" },
  { label: "模具状态", prop: "status", width: "120" },
  { label: "模具编码", prop: "mouldCode", width: "120" },
  { label: "模具型号", prop: "mouldSpecification", width: "120" },

  { label: "模具类型", prop: "mouldType", width: "120" },
  { label: "制造厂商", prop: "factoryName", width: "120" },
  { label: "出厂时间", prop: "factoryDate", width: "120" },
  { label: "领用次数", prop: "receiveNum", width: "120" },
  { label: "安装时间", prop: "installationTime", width: "120" },
  { label: "安装位置", prop: "installationSite", width: "120" },
  { label: "使用寿命(H)", prop: "serviceLife", width: "120" },
  { label: "已使用时长", prop: "utilityTime", width: "120" },

  { label: "备注", prop: "remark", width: "120" },
  { label: "创建人", prop: "createBy", width: "120" },
  { label: "创建时间", prop: "createTime", width: "120" },
  { label: "操作", prop: "x" },
]);

/**
 * 树结构
 */
const dataTree = ref([]);
/**
 * 树结构枚举
 */
const defaultProps = {
  children: "children",
  label: "categoryName",
  value: "id",
};
/**
 * 按钮枚举
 */
const buttonList = ref([
  { type: "add", hasPermi: "mold:edger:add" },
  { type: "import", hasPermi: "mold:edger:import" },
  // { type: "export", hasPermi: "mold:edger:export" },
]);

/**
 * 表格数据
 */
const tableData = ref([]);

/**
 * 表单实例
 */
const submitFormRef = ref(null);

/**
 * 一级类别列表
 */
const categoryList = ref([]);
/**
 * 新增修改表单
 */
const submitForm = ref({});

/**
 * 查询表单
 */
const query = reactive({
  pageNum: 1,
  pageSize: 10,
});

/**
 * 表单校验
 */
const rules = reactive({
  categoryName: [
    { required: true, message: "请填写类别名称", trigger: "change" },
  ],
});
/**
 * 各种状态
 */
const state = reactive({
  loading: false,
  total: 0,
  btnLoading: false,
  isShow: false,
  title: "新增",
  row: [],
  ids: [],
  treeShow: false, //树结构弹窗
});

/**
 * 新增弹窗
 */
const addDic = () => {
  state.title = "新增";
  state.isShow = true;
};

/**
 * 修改弹窗
 */
const editDic = async (id) => {
  try {
    state.btnLoading = true;
    const { data: result } = await GetViewAPI(id);
    submitForm.value = result;
    state.title = "修改";
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 查看弹窗
 */
const lookDic = async (id) => {
  try {
    state.btnLoading = true;
    const { data: result } = await GetViewAPI(id);
    submitForm.value = result;
    state.title = "查看";
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 弹窗关闭
 */
const closeDic = () => {
  state.isShow = false;
  state.treeShow = false;
  submitForm.value = {};
  ruleForm.value = {};
};

/**
 * 新增
 */
const addSub = async () => {
  try {
    state.btnLoading = true;
    const result = await submitFormRef.value.submit();
    await AddDataAPI(result);
    closeDic();
    proxy.successMsg("新增成功");
    getList();
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 修改
 */
const editSub = async () => {
  try {
    state.btnLoading = true;
    const result = await submitFormRef.value.submit();
    await EditDataAPI(result);
    closeDic();
    proxy.successMsg("修改成功");
    getList();
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 删除
 */
const remove = async (id) => {
  try {
    proxy.loading("删除中，请稍后");
    await DelDataAPI(id);
    closeDic();
    proxy.successMsg("删除成功");
    getList();
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

/**
 * 模糊查询
 */
const selectSubmit = (val) => {
  Object.keys(val).forEach((keyItem) => (query[keyItem] = val[keyItem]));
  query.startTime = query.beginTime;
  getList();
};

/**
 * 列表复选框
 */
const handleSelectionChange = ({ row, ids }) => {
  state.ids = ids;
  state.row = row;
};

/**
 * 类别新增弹窗
 */
const categoryAdd = async () => {
  try {
    const { data: res } = await moldDdlAPI();
    categoryList.value = res;
    state.treeShow = true;
  } catch (err) {
    console.log(err);
  }
};

/**
 * 类别下拉树结构
 */
const getTreeList = async () => {
  try {
    const { data: res } = await TreeListAPI();
    dataTree.value = res;
  } catch (err) {
    console.log(err);
  }
};
getTreeList();

/**
 * 类别新增保存
 */
const addTreeSub = async () => {
  try {
    console.log("AddCategoryAPI");

    state.btnLoading = true;
    const result = await ruleFormRef.value.validate();
    if (!result) return;
    await AddCategoryAPI(ruleForm.value);
    closeDic();
    proxy.successMsg("新增成功");
    getTreeList();
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 修改类别
 */
const editTree = async (v) => {
  console.log(v);
  try {
    state.btnLoading = true;
    const { data: res } = await moldDdlAPI();
    categoryList.value = res;
    state.treeShow = true;
    const { data: result } = await GetCategoryViewAPI(v.id);
    result.parentId = result.parentId == "0" ? "" : result.parentId;
    console.log(ruleForm.parentId, "ruleForm.parentId");
    ruleForm.value = result;
    state.title = "修改";
    state.treeShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 修改树结构提交
 */
const editTreeSub = async () => {
  try {
    state.btnLoading = true;
    const result = await ruleFormRef.value.validate();
    if (!result) return;
    await EditCategoryDataAPI(ruleForm.value);
    closeDic();
    proxy.successMsg("修改成功");
    getTreeList();
  } catch (err) {
    console.error(err);
  } finally {
    state.btnLoading = false;
  }
};

/**
 * 删除列表
 */
const delTree = async (v) => {
  try {
    const isif = await proxy.MessageBox("是否删除？");
    if (!isif) return;
    proxy.loading("删除中，请稍后");
    await DelCategoryAPI(v.id);
    closeDic();
    proxy.successMsg("删除成功");
    getTreeList();
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

/**
 * 查询列表
 */
const getList = async () => {
  try {
    state.loading = true;
    const result = await GetListAPI(query);
    state.total = result.total;
    tableData.value = result.rows;
  } catch (err) {
    console.error(err);
  } finally {
    state.loading = false;
  }
};

/**
 * 重置
 */
const close = () => {
  submitForm.value = {};
};
getList();
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" />
    <el-row :gutter="30">
      <el-col :span="5">
        <div class="grid-content ep-bg-purple" />
        <el-card class="card-tree">
          <template #header>
            <div class="card-header">
              <div>类别</div>
              <el-button
                type="primary"
                @click="categoryAdd"
                v-hasPermi="['mold:edger:ladd']"
                >新增</el-button
              >
            </div>
          </template>

          <el-tree
            :data="dataTree"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span
                  style="margin-right: 35px"
                  @click="getListFolder(node, data)"
                >
                  <!-- <el-icon
                    class="isShouzhi"
                    color="#4ca4ff"
                    v-if="data.children"
                    ><FolderOpened
                  /></el-icon> -->
                  {{ node.label }}
                </span>
                <span>
                  <el-tooltip
                    effect="dark"
                    content="修改"
                    placement="top-start"
                  >
                    <el-icon class="isShouzhi" color="#4ca4ff">
                      <Edit @click.stop="editTree(data)" />
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip
                    effect="dark"
                    content="删除此名称"
                    placement="top-start"
                  >
                    <el-icon color="red">
                      <Delete @click.stop="delTree(data)" />
                    </el-icon>
                  </el-tooltip>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <el-col :span="19">
        <div class="grid-content ep-bg-purple" />
        <!-- @export="
              proxy.download(
                '/system/planningInstruction/instructionExport',
                {}
              )
            " -->
        <el-card>
          <p-button
            :list="buttonList"
            @add="addDic"
            @import="getList"
            :url="'/system/mould/mouldTypeExportError'"
            :templateUrl="'/system/mould/download/excel'"
            :importUrl="'/system/mould/importData'"
          />
          <!-- 表格数据 -->
          <p-table
            class="tableClass"
            :loading="state.loading"
            :data="tableData"
            :column="columns"
            v-model:page="query.pageNum"
            v-model:limit="query.pageSize"
            :total="state.total"
            @change="handleSelectionChange"
            @pagination="getList"
          >
            <template #columnCell="{ column, record }">
              <!-- <p-Text
                v-if="column.prop == 'status'"
                :options="sys_tool_staus"
                :value="record.status"
              /> -->
              <p-operate
                :list="[
                  {
                    icon: 'Edit',
                    emit: 'edit',
                    disabled: false,
                    text: '修改',
                    type: 'primary',
                    hasPermi: 'mold:edger:edit',
                  },
                  {
                    icon: 'DeleteFilled',
                    emit: 'remove',
                    disabled: false,
                    text: '删除',
                    isDel: true,
                    type: 'danger',
                    hasPermi: 'mold:edger:remove',
                  },
                  {
                    icon: 'Search',
                    emit: 'look',
                    disabled: false,
                    text: '查看',
                    type: 'primary',
                    hasPermi: 'mold:edger:query',
                  },
                ]"
                v-if="column.prop == 'x'"
                @look="lookDic(record.id)"
                @edit="editDic(record.id)"
                @remove="remove(record.id)"
              />
            </template>
          </p-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 新增-修改 -->
    <p-dialog
      v-model="state.isShow"
      :title="state.title"
      @ok="state.title == '新增' ? addSub() : editSub()"
      @close="close"
      width="60%"
    >
      <SubmitForm
        ref="submitFormRef"
        :data="submitForm"
        :disabled="state.title == '查看'"
      />
    </p-dialog>
    <!-- 树结构类别 -->
    <p-dialog
      v-model="state.treeShow"
      :title="state.title"
      @ok="state.title == '新增' ? addTreeSub() : editTreeSub()"
      @close="closeDic"
      width="30%"
    >
      <el-form
        :model="ruleForm"
        label-width="120px"
        :rules="rules"
        status-icon
        inline
        ref="ruleFormRef"
      >
        <el-form-item label="类型名称" prop="categoryName">
          <el-input clearable v-model="ruleForm.categoryName" />
        </el-form-item>
        <el-form-item label="模具类型">
          <p-select
            :option="categoryList"
            v-model="ruleForm.parentId"
            placeholder="请选择模具类型"
          />
        </el-form-item>
      </el-form>
    </p-dialog>
  </div>
</template>

<style scoped lang="scss">
.card-tree {
  height: 52.5rem;
  overflow: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
}
</style>